package datastructure.queue;

public class LoopQueue<E> implements Queue<E> {
    private E[] data;
    private int front;
    private int tail;
    private int size;

    @SuppressWarnings("unchecked")
    public LoopQueue(int capacity) {
        data = (E[]) new Object[capacity + 1];
        //指向第一个元素所在的位置
        front = 0;
        //指向下一个将要入队元素的位置  开始为0，符合语意
        tail = 0;
        size = 0;
    }

    public LoopQueue() {
        this(10);
    }

    // 入队操作
    @Override
    public void enqueue(E e) {
        // 首先判断一下是否还有容量
        if ((tail + 1) % data.length == front) {
            resize(getCapacity() * 2);
        }

        data[tail] = e;
        // 维护队尾和size
        tail = (tail + 1) % data.length;
        size++;

    }

    private void resize(int capacity) {
        E[] newData = (E[]) new Object[capacity + 1];
        // 将对列中元素copy到新的对列中
        for (int i = 0; i < size; i++) {
            newData[i] = data[(front + i) % data.length];
        }
        data = newData;
        // 维护队首和队尾元素指向
        front = 0;
        tail = size;
    }

    @Override
    public E dequeue() {
        // 判断是否为空
        if (isEmpty()) {
            throw new IllegalArgumentException("对列已经为空,没有元素了");
        }
        E ret = data[front];
        // 维护队首
        data[front] = null;
        front = (front + 1) % data.length;
        size--;
        // 容量的收缩
        if (size == getCapacity() / 4 && getCapacity() / 2 != 0) {
            resize(getCapacity() / 2);
        }
        return ret;
    }

    @Override
    public E peek() {
        return data[front];
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return front == tail;
    }

    // 为了弥补浪费掉的哪一个空间,就在创建的时候使用了+1操作,所以这里长度需要减掉1
    public int getCapacity() {
        return data.length - 1;
    }

    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();
        sb.append("LoopQueue: size=" + size + "\tcapacity=" + getCapacity() + "\n");
        sb.append("front [");
        for (int i = front; i != tail; i = (i + 1) % data.length) {
            sb.append(data[i]);
            if ((i + 1) % data.length != tail) {
                sb.append(",");
            }

        }
        sb.append("]");
        return sb.toString();
    }

    public static void main(String[] args) {
        LoopQueue<Integer> queue = new LoopQueue<>();

        for (int i = 0; i < 10; i++) {
            queue.enqueue(i);
            System.out.println(queue);
            if (i % 3 == 2) {
                System.out.println(queue.dequeue());
            }
        }

    }
}
